const mongoose = require('mongoose');
const Comment = require('../models/comment.models');
const Cate = require("../models/cate.models");
const News = require('../models/news.models');

//新增数据
exports.create = function (req, res, next) {
  const comment = new Comment(req.body);
  comment.save().then(data => {
    res.json(data);
  });
};

//根据ID获取指定数据
exports.get = function (req, res, next) {
  const id = req.params.id;

  Comment.findById(id, (err, result) => {
    res.json(result)
  });
};

//根据ID更新指定数据
exports.update = function (req, res, next) {
  const id = req.params.id;
  Comment.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
    res.json(data);//data:更新之前的数据
  })
};

//根据ID删除指定数据
exports.delete = function (req, res, next) {
  const id = req.params.id;
  Comment.findByIdAndRemove(id, function (err, doc) {
    res.json({ message: '数据删除成功', status: 200 });
  })
};

/**
 * 删除多条数据数据
 * @param {String} ids:要删除数据的id的集合字符串，用‘，’隔开
 */
exports.removes = function (req, res, next) {
  const ids = req.body.ids.split(',');//将id拆分成数组

  if (ids.length > 0) {
    Comment.remove({ _id: { $in: ids } }).then(data => {
      res.json({ status: 200, message: '删除多条数据成功' });
    });
  }
}

//根据newsId删除该news的所有评论
exports.removesByNewsId = function (req, res, next) {
  const id = req.params.newsId;
  Comment.remove({ newsId: id }).then(data => {
    res.json({ status: 200, message: '已成功删除该新闻下的所有评论' })
  })
}

/**
 * 根据newsId获取数据列表
 * @param {*} page:页码 
 * @param {*} rows:每页条数
 * @param {*} quertCondition:查询条件
 */
exports.list = function (req, res, next) {
  var page = req.body.page ? req.body.page : 1;
  var rows = req.body.rows ? req.body.rows : 5;
  var newsId = req.body.newsId;
  var quertCondition = {};
  
  //查询参数少请用这里
  if (req.body.newsId && req.body.newsId.trim().length > 0) {
    quertCondition = {
      paths: new RegExp(req.body.newsId, 'i')
    }
  }

  if (req.body.content && req.body.content.trim().length > 0) {
    //对象合并
    quertCondition = Object.assign(quertCondition, {
      content: new RegExp(req.body.content, 'i')
    });
  }

  Comment.paginate(quertCondition, { page: +page, limit: +rows }, function (err, result) {
    result.rows = result.docs;
    delete result.docs;
    res.json(result);
  });
};

//制作树型菜单
exports.tree = function(req, res, next) {
  var type = req.params.type;
  Cate.find({ type: type }, function(err, data) {
    var rpTree = reverseTree(data, null);

    //获取最终异步处理数据，并传递到前台
    someAsyncMethod(rpTree).then(result => {
      res.json(result);
    });
  });
};

//使用递归实现树
function reverseTree(data, pid) {
  var result = [],
    temp;

  var data = JSON.parse(JSON.stringify(data)); //将数据模型对象转成字符串，然后将字符串转成对象，这个时候就可以给data里增加节点children
  for (var i in data) {
    if (data[i].parentId === pid) {
      //如果数据中的parentId和传进来的pid相等,把当前的数据push进一个数组里
      result.push(data[i]);

      temp = reverseTree(data, data[i]._id);
      if (temp.length > 0) {
        data[i].children = temp;
      }
    } 
    }
  
  return result;
}

//通过P肉糜se.all执行新闻数组中的promise，获取新闻数据数组
 const someAsyncMethod = (data) => {
    return new Promise(resolve => {
      let arr =  getArr(data);
      let promise = Promise.all(arr);

      promise.then(val => {
        let totalArr = [];
        //二元数组拍平
        for (let i = 0,len = val.length; i < len; i++) {
            totalArr = totalArr.concat(val[i]);
        }
        resolve(getData(data,totalArr));
      })
   });
 }

 //对获取的新闻的Promise.resolve数组与data分类进行匹配，添加到所属分类children中去
 function getData(data,arr) {
   //遍历data和新闻数组，进行匹配
    data.forEach(ele => {
        arr.forEach((e,i) => {
          if(ele._id == e.cateid){
            //添加text，值为title，使前端页面tree中可以显示news标题 
              e.text = e.title;
              //判断该分类是否拥有children属性
              if(ele.children) {
                ele.children.push(e);
              } else {
                ele.children = [e];
              }
          }
        });

        //递归
        if(ele.children) {
            ele.children = getData(ele.children,arr);
        }
    });
    return data;
 }

 //利用递归和循环遍历，获取getNews的Promise.resolve数组
 function getArr(data) {
    let arr = [];
    for(let i = 0,len = data.length; i < len;i++) {
        arr.push(getNews(data[i]._id))
        if(data[i].children) {
          arr = arr.concat(getArr(data[i].children));
        }
    }
    return arr;
 }

 //根据分类id查询该分类下的新闻
 const getNews = (id) => {
   return new Promise(resolve => {
      News.find({cateid: id},(err,result) => {
          let resultArr = JSON.parse(JSON.stringify(result));
          resolve(resultArr);
      });
   });
 }